package com.zengqingfa.odd;

/**
 * @fileName: PrintOddEven1
 * @author: zengqingfa
 * @date: 2022/12/14 17:39
 * @description:
 */
public class PrintOddEven1 {

    public static int count;

    public static final Object object = new Object();

    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (count < 100) {
                    synchronized (object) {
                        if (count % 2 == 1) {
                            System.out.println(Thread.currentThread().getName() + ":" + count++);
                            object.notify();
                        } else {
                            try {
                                object.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }, "奇数线程").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (count < 100) {
                    synchronized (object) {
                        if (count % 2 == 0) {
                            System.out.println(Thread.currentThread().getName() + ":" + count++);
                            object.notify();
                        } else {
                            try {
                                //等待
                                object.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }, "偶数线程").start();
    }

}
